# -*-coding:utf-8 -*-
# author: leemon
# datetime: 2020/6/03 13:37
import json

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

# you need to modify the SecretId and SecretKey
SecretId = 'AKID3ud8NMxP6XineHwutdIj6ExQhkZYn0Uj'
SecretKey = 'Em5B1c8vTlslPxFTSCj4A1dyDDuMcdQx'
EndPoint = 'cvm.tencentcloudapi.com'
Region = 'ap-shanghai'


class TencentCvmApi:
    def __init__(self, secretid, secretkey, endpoint='cvm.tencentcloudapi.com', region='ap-shanghai'):
        self.secretid = secretid
        self.secretkey = secretkey
        self.endpoint = endpoint
        self.region = region
        self.client = self.get_client()

    def get_client(self):
        try:
            cred = credential.Credential(self.secretid, self.secretkey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = self.endpoint

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = cvm_client.CvmClient(cred, self.region, clientProfile)
        except:
            pass
        else:
            return client

    def get_cvm(self, limit=100, offset=0):
        try:
            client = self.client

            req = models.DescribeInstancesRequest()
            if limit != 0:
                params = '{"Limit":%d, "Offset":%d}' % (limit, offset)
            else:
                params = '{}'
            req.from_json_string(params)

            resp = client.DescribeInstances(req)
            resp_json = json.loads(resp.to_json_string())

        except TencentCloudSDKException as err:
            print(err)
        else:
            instance_set = resp_json.get('InstanceSet', False)
            total_count = resp_json.get('TotalCount')
            cleaned_instance = []
            result = {"TotalCount": total_count}
            tmp = {}
            if instance_set:
                for instance in instance_set:
                    tmp = {'sn': instance.get('InstanceId'), 'cpu_core_count': instance.get('CPU'),
                           'mem_capacity': instance.get('Memory'), 'productmodel': instance.get('InstanceType'),
                           'os_release': instance.get('OsName'),
                           'ip_management': ','.join(instance.get('PrivateIpAddresses'))}
                    cleaned_instance.append(tmp)
            result["InstanceSet"] = cleaned_instance
            return result

    def get_all(self):
        instances = []
        offset = 0
        flag = True
        while True:
            res = self.get_cvm(offset=offset)
            if flag:
                total_count = res.get('TotalCount')
            tmp = res.get('InstanceSet')
            instances.extend(tmp)

            if int(total_count / 100) > 0:
                flag = False
                total_count = total_count - 100
                offset += 100
                continue
            else:
                break
        return instances


if __name__ == '__main__':
    tencent_cvm_api = TencentCvmApi(SecretId, SecretKey, EndPoint, Region)
    instances = tencent_cvm_api.get_all()
    print(instances)
    print(len(instances))
